package com.tdam2014.grupo3.flickr.util;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

import com.tdam2014.grupo3.flickr.Parameter;


public class URLUtils {
	
	public static final String NO_SUFFIX = "";
	public static final String SQUARE_150_IMAGE_SUFFIX = "_q";
	
	public static String getImageUrl(int farm, String server, String id, String secret, String suffix) {
		String imageUrl = "https://farm" 
							+ farm + ".staticflickr.com/"
							+ server + "/"
							+ id + "_"
							+ secret
							+ suffix + ".jpg";
        return imageUrl;
    }
	
    public static String getBuddyIconUrl(int iconFarm, int iconServer, String nsid) {
        String iconUrl = "https://farm"
		    				+ iconFarm + ".static.flickr.com/"
							+ iconServer + "/buddyicons/"
							+ nsid + ".jpg";
        return iconUrl;
    }
    
    public static URL buildUrl(String host, int port, String path, List<Parameter> parameters) throws MalformedURLException {
        StringBuffer buffer = new StringBuffer();
        buffer.append("https://");
        buffer.append(host);
        if (port > 0 & port != 80) {
            buffer.append(":");
            buffer.append(port);
        }
        if (path == null) {
            path = "/";
        }
        buffer.append(path);

        Iterator<Parameter> iter = parameters.iterator();
        if (iter.hasNext()) {
            buffer.append("?");
        }
        while (iter.hasNext()) {
            Parameter p = (Parameter) iter.next();
            buffer.append(p.getName());
            buffer.append("=");
	        Object value = p.getValue();
	        if (value != null) {
		        String string = URLUtils.encode(value.toString());
		        buffer.append(string);
	        }
            if (iter.hasNext()) buffer.append("&");
        }
        
        return new URL(buffer.toString());
    }
    
    public static String encode(String value) {
        String encoded = null;
        try {
            encoded = URLEncoder.encode(value, "UTF-8");
        } catch (UnsupportedEncodingException ignore) {}
        StringBuffer buf = new StringBuffer(encoded.length());
        char focus;
        for (int i = 0; i < encoded.length(); i++) {
            focus = encoded.charAt(i);
            if (focus == '*') {
                buf.append("%2A");
            } else if (focus == '+') {
                buf.append("%20");
            } else if (focus == '%' && (i + 1) < encoded.length()
                    && encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') {
                buf.append('~');
                i += 2;
            } else {
                buf.append(focus);
            }
        }
        return buf.toString();
    }
}